# coding=utf-8

from BaseController import BaseController
#from Utility import FormData
from Utility import SessionKey
from Utility import IsEmptyString
from Configuration import EXTERNAL_QUESTION_URL
import re
from Common.MTurk.CreateExternalHITParams import CreateExternalHITParams
from Biz import MTurkRequester
from datetime import date
from datetime import timedelta
import datetime

class PreviewHITController(BaseController):
    def get(self):
        hitdata = self.GetSessionItem(SessionKey.CURRENT_HIT_DATA)
        hitcsvdata = self.GetSessionItem(SessionKey.CURRENT_HIT_CSV_DATA)
        if hitdata is None or hitcsvdata is None:
            return self.response.out.write("HIT data cannot be empty")
        
        """
        If hit index is not empty, we will return hit partial view.
        """
        hitindex = self.request.get("index")
        if not IsEmptyString(hitindex):
            
            try:
                hitindex = int(hitindex)
            except ValueError:
                return self.response.out.write("HIT index was out of range")
            
            if hitindex > len(hitdata) or hitindex < 1:
                self.response.out.write("HIT index was out of range")
            else:
                self.response.out.write(hitdata[hitindex - 1].QuestionForm)
            return

        """
        By default display the first hit data.
        """
        if hitdata is not None:
            if len(hitcsvdata) > 1:
                for i in range(len(hitcsvdata[0])):
                    hitcsvdata[0][i] = hitcsvdata[0][i][2:-1]
            template_values = {"requester":hitdata, "reward":"$0.03 per HIT", "hitavailable":2, "duration":"1 hour",
                               "qualifications":"HIT Approval Rate (%)  greater than or equal to  95",
                               "QuestionForm":hitdata[0].QuestionForm, "item_list_count":len(hitdata), "items":hitcsvdata}
            self.Render("hit_preview", template_values)
            
    def post(self):
        template_values = {}
        hitdata = self.GetSessionItem(SessionKey.CURRENT_HIT_DATA)
        if hitdata is None:
            template_values["message"] = "HIT data cannot be empty"
            return self.Render("hit_preview_response", template_values)
        
        hitindex = self.request.get("index")
        hitId = []
        if not IsEmptyString(hitindex):
            p = re.compile('\d')
            index = set(p.findall(hitindex))
            if len(index) > 0:            
                hitdatalen = len(hitdata)
                for i in index:
                    try:
                        ival = int(i)
                        if ival >= 1 and ival <= hitdatalen:
                            #
                            # send hit data.
                            #
                            currentHit = hitdata[ival - 1]
                            currentHit.HITId = "" 
                            currentHit.CreatedDate = datetime.datetime.now()
                            currentHit.put()
                            
                            p = CreateExternalHITParams(title=currentHit.Title,
                                  description=currentHit.Description,
                                  keywords=currentHit.Keywords,
                                  reward={'Amount':currentHit.Amount, 'CurrencyCode':'USD'},
                                  maxAssignments=currentHit.MaxAssignments,
                                  lifetimeInSeconds=currentHit.LifetimeInSeconds,
                                  assignmentDurationIn=currentHit.AssignmentDurationInSeconds,
                                  question='<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"><ExternalURL>' + EXTERNAL_QUESTION_URL + str(currentHit.key().id_or_name()) + '</ExternalURL><FrameHeight>400</FrameHeight></ExternalQuestion>')
                            resdom = MTurkRequester.SendMTurkRequest(p)
                            """
                            Url: http://mechanicalturk.sandbox.amazonaws.com/?AWSAccessKeyId=AKIAIWRSYEUADSMOX4RQ&MaxAssignments=1&Service=AWSMechanicalTurkRequester&Title=Answer+a+question&Timestamp=2011-03-20T14%3A23%3A43Z&Question=%3CExternalQuestion+xmlns%3D%22http%3A%2F%2Fmechanicalturk.amazonaws.com%2FAWSMechanicalTurkDataSchemas%2F2006-07-14%2FExternalQuestion.xsd%22%3E%3CExternalURL%3Ehttp%3A%2F%2Ftictactoe.amazon.com%2Fgamesurvey.cgi%3Fgameid%3D01523%3C%2FExternalURL%3E%3CFrameHeight%3E400%3C%2FFrameHeight%3E%3C%2FExternalQuestion%3E&AssignmentDurationInSeconds=3600&AutoApprovalDelayInSeconds=86400&Version=2008-02-14&Signature=Jaxe7ks48kEDnNeCzKNuU5%2FKxOc%3D&Keywords=hello%2C+world%2C+command%2C+sample%2C+question%2C+answer&Operation=CreateHIT&Reward.1.Amount=0.02&Reward.1.CurrencyCode=USD&LifetimeInSeconds=259200&Description=Please+provide+a+short+answer+to+this+question.
                            
                            Failed:
                            <?xml version="1.0"?> 
                            <Response>
                              <Errors>
                                <Error>
                                  <Code>RequestExpired</Code>
                                  <Message>Request has expired. Timestamp date is 2011-03-20T14:23:43Z</Message>
                                </Error>
                              </Errors>
                            <RequestID>33d7dd72-e9ef-4a6d-bb39-d8f75d9704bf</RequestID>
                            </Response>
                            
                            Success:
                            <?xml version="1.0"?> 
                            <CreateHITResponse>
                              <OperationRequest>
                                <RequestId>f5be3fd1-6fe1-47ee-8d86-f1932dd052d9</RequestId>
                              </OperationRequest>
                              <HIT>
                                <Request>
                                  <IsValid>True</IsValid>
                                </Request>
                                <HITId>1IJKC9R1UWURPIAEV7XU0FCD5SSFHH</HITId>
                                <HITTypeId>1G2OJ1T2JR9N3BQNZUCFT0ONNWA5EY</HITTypeId>
                              </HIT>
                            </CreateHITResponse>
                            """                
                            if resdom is not None:
                                if resdom.getElementsByTagName("HIT"):
                                    isValid = self.getText(resdom.getElementsByTagName("IsValid")[0].childNodes)
                                    if isValid == "True":
                                        amazonHitId = self.getText(resdom.getElementsByTagName("HITId")[0].childNodes)
                                        currentHit.HITId = amazonHitId
                                        currentHit.put()
                                        createdHit = {"duration":currentHit.getDurationText()}
                                        createdHit['title'] = currentHit.Title
                                        createdHit['reward'] = currentHit.Amount
                                        createdHit['campaign'] = currentHit.Ref_Campaign.CampaignName
                                        createdHit['expiration'] = currentHit.getExpirationText()
                                        createdHit['client'] = currentHit.Ref_Client.ClientName
                                        hitId.append(createdHit)
                            else:
                                self.response.out.write("You got an error from Amazon")
                                return
#                            self.response.out.write(hitdata[ival - 1].QuestionForm + "<br/>")
                    except ValueError:
                        #
                        # does nothing
                        #
                        self.response.out.write("Invalid index data:" + i)
                        return
            
            if len(hitId) == 0:
                template_values["message"] = "There were no HITs created"
            elif len(hitId) == 1:
                template_values["message"] = "There was one HIT created"
                template_values["isok"] = True
            else:
                template_values["message"] = "There were " + str(len(hitId)) + " HITs created"
                template_values["isok"] = True
        else:
            template_values["message"] = "There were no HITs selected"
        if template_values["isok"] is None:
            template_values["isok"] = False
        else:
            template_values["createdHits"] = hitId
        self.Render("hit_preview_response", template_values)
        
    def getText(self, nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)

            
